<!--
- File:    购物车列表.
-->
<template>
  <div>
    <div class="Web_Box" style="padding-top:45px;">
      <div class="con_tab">
        <ul class="f-cb">
          <li :class="{'cur': cartType == $dictionary.cartType.buy }" @click="switchCartType($dictionary.cartType.buy)">买花</li>
          <li :class="{'cur': cartType == $dictionary.cartType.rent }" @click="switchCartType($dictionary.cartType.rent)">租花</li>
        </ul>
      </div>
      <!--店铺商品Start-->
      <div class="ShoppingCartPage">
        <div class="ShopGoods EditPro f-cb  mb10" v-for="store in cartList.data.store_list" v-show="getGoodCountByStore(store.store_id) > 0">
          <div class="storetit">
            <i class="iconfont icon-pitchon2" @click="switchSelectAllByStore(store.store_id, false)" v-if="getGoodsSelectedCountByStore(store.store_id) == getGoodCountByStore(store.store_id)"></i>
            <i class="iconfont icon-pitch2" @click="switchSelectAllByStore(store.store_id, true)" v-else></i>
            <span>{{store.store_name}}</span>
          </div>
          <div class="ProList bg_f5f5f5">
            <ul>
              <li v-for="item in cartList.data.cart_list" v-if="item.store_id == store.store_id">
                <div class="Choice" @click="switchSelect(item)">
                  <i class="iconfont icon-pitch2" v-if="indexInSelected(item) == -1"></i>
                  <i class="iconfont icon-pitchon2" v-else></i>
                </div>
                <div class="Pic">
                  <img :src="$config.imgsite + $config.goodsImgSrc + item.store_id + '/' + item.goods_image + '_w150'" alt=""/></div>
                <div class="Con" style="width: 10.5rem;">
                  <div class="pl20 f-cb">
                    <span class="detete" @click="delGoodsFromCart(item)"><i class="iconfont icon-del3" style="padding:0 5px"></i></span>
                    <h2 class="" style="width: 80%; margin: 0 !important;">
                      <span @click="gotoGoodsDetail(item.store_id, item.goods_commonid)">{{item.goods_name}}</span></h2>
                  </div>
                  <div class="cr_898989 pl20" v-show="(item.goods_storage && item.goods_storage <= 0) || item.goods_state != '1'">
                    <i class="iconfont icon-shixiao"></i>
                  </div>
                  <div class="pl20">
                    <p class="Attribute" style="font-size: 12px; margin-bottom: 0; height: auto" v-show="item.goods_spec.length > 0">
                      <span v-for="attr in item.goods_spec">{{attr.name}} </span></p>
                    <div class="PriceQuantity f-cb" v-show="item.goods_storage > 0">
                      <span class="fl cr_ea5413">￥{{item.goods_price | discount(item.groupbuy_rebate)}}</span>
                      <div class="Edit">
                        <i class="iconfont icon-jian1" :class="{'jian1-active': parseInt(item.goods_num) > 1}" @click="reduceNum(item)"></i>
                        <span class="num">{{item.goods_num}}</span>
                        <i class="iconfont icon-jia1" @click="addNum(item)"></i>
                      </div>
                    </div>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <!--店铺商品End-->
    </div>
    <div class="ShopGoodsOperation BottomGd">
      <div class="left fl">
        <!--<i class="iconfont icon-pitchon2" @click="switchSelectAll(false)" v-if="selectedGoodsList.length > 0 && selectedGoodsList.length === cartList.data.cart_list.length"></i>-->
        <!--<i class="iconfont icon-pitch2" @click="switchSelectAll(true)" v-else></i>-->
        <!--<span class="text">全选</span>-->
        <div class="Statistics fr tr">
          <p class="Total">合计：<span class="cr_ea5413">￥{{totalPrice}}</span></p>
          <p class="Freight" style="background-color: transparent">不含运费</p>
        </div>
      </div>
      <div class="right fr">
        <button type="button" class="but" :class="{'confirm-unactive': totalNum <= 0}" @click="gotoOrderConfirm">结算({{totalNum}})</button>
      </div>
    </div>
    <div class="Cart_nodata" v-show="cartList.requested && cartList.data.cart_list.length <= 0">
      <i class="iconfont icon-kong"></i>
      <p>购物车还是空的哦</p>
      <a href="javascript:void(0)" @click="gotoHome">去逛逛</a>
    </div>
    <back-nav></back-nav>
  </div>
</template>

<script>
  //  import {mapModules, mapRules} from 'vuet'

  export default{
    data() {
      return {
        cartType: this.$dictionary.cartType.buy,
        cartList: {requested: false, data: {cart_list: [], store_list: []}},
        selectedGoodsList: []
      }
    },
    computed: {
      totalPrice: function () {
        let total = 0
        for (let i = 0; i < this.selectedGoodsList.length; i++) {
          total += parseFloat(this.selectedGoodsList[i].goods_price) * parseFloat(this.selectedGoodsList[i].groupbuy_rebate / 100) * parseInt(this.selectedGoodsList[i].goods_num)
          continue
        }
        return total.toFixed(2)
      },
      totalNum: function () {
        let total = 0
        for (let i = 0; i < this.selectedGoodsList.length; i++) {
          total += parseInt(this.selectedGoodsList[i].goods_num)
        }
        return total
      }
    },
    components: {},
    created() {
      this.getCartList(this.cartType)
    },
    methods: {
      gotoHome() {
//        this.$router.push({name: 'home'})
        window.location.href = 'http://' + window.location.host + '/wap/' // ios微信分享要如此跳转后才能正确分享
      },
      gotoGoodsDetail(storeId, goodsCommonid) {
        this.$router.push({name: 'goods-detail', params: {id: goodsCommonid}, query: {storeId: storeId}})
      },
      gotoOrderConfirm() {
        if (this.selectedGoodsList.length <= 0) {
          this.$toast('请先选择要结算的商品')
          return
        }
        let storeIdTmp = this.selectedGoodsList[0].store_id
        for (let i = 0; i < this.selectedGoodsList.length; i++) {
          if (this.selectedGoodsList[i].store_id != storeIdTmp) { // 购物车限制只能单店结算
            this.$toast('请选择同店商品结算')
            return
          }
          storeIdTmp = this.selectedGoodsList[i].store_id
        }
        let selectedCartIdList = []
        for (let i = 0; i < this.selectedGoodsList.length; i++) {
          selectedCartIdList.push(this.selectedGoodsList[i].cart_id)
        }
        let cartIdListStr = selectedCartIdList.join(',')
        if (this.cartType == this.$dictionary.cartType.buy) { // 买
          this.$router.push({name: 'order-confirm', query: {cart: cartIdListStr}})
        } else if (this.cartType == this.$dictionary.cartType.rent) {
          this.$router.push({name: 'order-rent-confirm', query: {cart: cartIdListStr}})
        }
      },
      switchCartType(type) {
        this.cartType = type
        this.cartList = {requested: false, data: {cart_list: [], store_list: []}}
        this.selectedGoodsList = []
        this.getCartList(type)
      },
      findGoodsInCartList(cartId) {
        for (let i = 0; i < this.cartList.data.cart_list.length; i++) {
          if (this.cartList.data.cart_list[i].cart_id === cartId) {
            return {goods: this.cartList.data.cart_list[i], index: i}
          }
        }
        return {goods: null, index: -1}
      },
      indexInSelected(goods) {
        for (let i = 0; i < this.selectedGoodsList.length; i++) {
          if (this.selectedGoodsList[i].cart_id == goods.cart_id) {
            return i
          }
        }
        return -1
      },
      addSelect(goods) {
        if (this.indexInSelected(goods) == -1) {
          this.selectedGoodsList.push(goods)
        }
      },
      delSelect(goods) {
        let index = this.indexInSelected(goods)
        if (index != -1) {
          this.selectedGoodsList.splice(index, 1)
        }
      },
      switchSelect(goods) {
        if (goods.goods_state != '1') {
          this.$toast('该商品已失效，不能购买')
          return
        }
        let index = this.indexInSelected(goods)
        if (index != -1) { // 已选
          this.delSelect(goods)
        } else { // 未选
          this.addSelect(goods)
        }
      },
      getGoodCountByStore(storeId) {
        let count = 0
        for (let i = 0; i < this.cartList.data.cart_list.length; i++) {
          if (this.cartList.data.cart_list[i].store_id == storeId) {
            count++
          }
        }
        return count
      },
      getGoodsSelectedCountByStore(storeId) {
        let count = 0
        for (let i = 0; i < this.selectedGoodsList.length; i++) {
          if (this.selectedGoodsList[i].store_id == storeId) {
            count++
          }
        }
        return count
      },
      switchSelectAllByStore(storeId, boolValue) {
        if (!boolValue) { // 全不选
          for (let i = this.selectedGoodsList.length - 1; i >= 0; i--) {
            if (this.selectedGoodsList[i].store_id == storeId) {
              this.delSelect(this.selectedGoodsList[i])
            }
          }
        } else { // 全选
          for (let i = 0; i < this.cartList.data.cart_list.length; i++) {
            if (this.cartList.data.cart_list[i].store_id == storeId && this.cartList.data.cart_list[i].goods_state == '1') {
              this.addSelect(this.cartList.data.cart_list[i])
            }
          }
        }
      },
      switchSelectAll(boolValue) {
        if (!boolValue) { // 全不选
          this.selectedGoodsList = []
        } else { // 全选
          let tmpArray = []
          for (let i = 0; i < this.cartList.data.cart_list.length; i++) {
            tmpArray.push(this.cartList.data.cart_list[i])
          }
          this.selectedGoodsList = tmpArray
        }
      },
      addNum(goods) {
        if (parseInt(goods.goods_num) >= parseInt(goods.goods_storage)) {
          this.$toast('超过商品库存数量了~')
          return
        }
        this.$request.modifyGoodsNumToBuy(goods.cart_id, parseInt(goods.goods_num) + 1).then(() => {
          let goodsEdit = this.findGoodsInCartList(goods.cart_id).goods
          goodsEdit.goods_num++
        }).catch(e => {
          this.$toast('修改购买数量失败:' + e.msg)
        })
      },
      reduceNum(goods) {
        if (parseInt(goods.goods_num) <= 1) {
          return
        }
        this.$request.modifyGoodsNumToBuy(goods.cart_id, goods.goods_num - 1).then(() => {
          let goodsEdit = this.findGoodsInCartList(goods.cart_id).goods
          goodsEdit.goods_num--
        }).catch(e => {
          this.$toast('修改购买数量失败' + e.msg)
        })
      },
      getCartList(cartType) {
        this.$request.getCartList(cartType).then(data => {
          this.cartList.data.cart_list = data.cart_list
          this.cartList.data.store_list = data.store_list
        }).catch(e => {
          console.error(e)
          this.$toast('获取购物车列表失败:' + e.msg)
        }).finally(() => {
          this.cartList.requested = true
        })
      },
      delGoodsFromCart(goods) {
        this.$messageBox.confirm(`你确定要删除该商品吗?`).then(action => {
          this.$request.delGoodsFromCart(goods.cart_id).then(data => {
            let index = this.findGoodsInCartList(goods.cart_id).index
            this.cartList.data.cart_list.splice(index, 1)
            let index2 = this.indexInSelected(goods)
            if (index2 != -1) {
              this.delSelect(goods)
            }
            this.$toast('删除成功')
          }).catch(e => {
            this.$toast('删除购物车失败:' + e.msg)
          })
        }).catch(() => {
        })
      }
    }
  }
</script>

<style>
  .no-margin-bottom {
    margin-bottom: 0;
  }

  .jian1-active {
    color: #45a73a !important;
  }

  .confirm-unactive {
    background-color: #dddddd !important;
  }
</style>